package com.shelpe.services.tenant.controller;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.shelpe.services.tenant.dto.AuthDto;
import com.shelpe.services.tenant.dto.RptCustomerDto;
import com.shelpe.services.tenant.jobclient.AuthClient;
import com.shelpe.services.tenant.jobclient.SyncSchedulerClient;

@RestController
@RequestMapping(value="/jobserver")
public class AuthController {
	
	private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
	
	@Value("${jobserver.mainInnerUserId}")
	private String mainInnerUserId;
	
	@Autowired
	private AuthClient authClient;
	
	@Autowired
	private SyncSchedulerClient scheduleClient;
	
	private final ExecutorService executor = Executors.newSingleThreadExecutor();
	
	@RequestMapping("/syncuserauth")
	@ResponseBody
	public AuthDto syncUserAuth(){
		
		AuthDto dto = new AuthDto();
		
		CompletionService<AuthDto> comletionService = new ExecutorCompletionService<AuthDto>(executor); 
		
		comletionService.submit(new Callable<AuthDto>(){

			@Override
			public AuthDto call() throws Exception {
				// TODO Auto-generated method stub
				if(mainInnerUserId != null){
					
					String[] mainUserIds = mainInnerUserId.split(",");
					//logger.info(">>>> mainInnerUserId {}, length {}", mainInnerUserId, mainUserIds.length);
					if(mainUserIds != null && mainUserIds.length > 0){
						for(int i = 0; i < mainUserIds.length; i++){
							
							RptCustomerDto dto = authClient.syncAuthorizeByUser(mainUserIds[i]);
							
							List<Long> newUserIds = dto.getNewUserIds();							
							if(newUserIds != null && newUserIds.size() > 0){
								for(Long userId : newUserIds){
									
									scheduleClient.syncUserJob(userId);
								}
							}//对于新的用户，及时刷新一下
							
							List<Long> updateUserIds = dto.getUpdateUserIds();
							if(updateUserIds != null && updateUserIds.size() > 0){
								for(Long userId : updateUserIds){
									
									scheduleClient.syncUserJob(userId);
								}
							}//转绑用户也更新一下
						}
					}
				}
				
				return null;
			}
		});

		dto.setMessage("success");
		
		return dto;
	}
	

}
